package com.kecheng.servermonitor.util;

import java.io.File;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.List;

import com.kecheng.servermonitor.entity.DiskUsage;
import com.sun.management.OperatingSystemMXBean;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;

/**
 * 系统监控工具类
 * 用于获取内存、CPU和磁盘使用率信息
 */
public class SystemMonitorUtil {

    /**
     * 获取内存使用率
     *
     * @return 内存使用率百分比（0-100）
     */
    public static int getMemoryUsage() {
        try {
            OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
            long totalvirtualMemory = osmxb.getTotalPhysicalMemorySize();
            long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize();
            double value = (double) freePhysicalMemorySize / totalvirtualMemory;
            return (int) ((1 - value) * 100);
        } catch (Exception e) {
            // 备用方案：使用Runtime获取内存信息
            Runtime runtime = Runtime.getRuntime();
            long totalMemory = runtime.totalMemory();
            long freeMemory = runtime.freeMemory();
            long usedMemory = totalMemory - freeMemory;
            double memoryUsage = (double) usedMemory / totalMemory;
            return (int) (memoryUsage * 100);
        }
    }

    /**
     * 获取CPU使用率
     *
     * @return CPU使用率百分比（0-100）
     */
    public static double getCpuUsageWithOshi() {
        try {
            SystemInfo systemInfo = new SystemInfo();
            CentralProcessor processor = systemInfo.getHardware().getProcessor();

            // JDK 8兼容的CPU使用率获取方式
            long[] oldTicks = processor.getSystemCpuLoadTicks();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return 0;
            }
            long[] newTicks = processor.getSystemCpuLoadTicks();

            long total = 0;
            for (int i = 0; i < newTicks.length; i++) {
                total += newTicks[i] - oldTicks[i];
            }

            long idle = newTicks[CentralProcessor.TickType.IDLE.getIndex()] -
                    oldTicks[CentralProcessor.TickType.IDLE.getIndex()];

            double cpuUse = 0;
            if (total > 0) {
                cpuUse = (1.0 - (double) idle / total) * 100;
            }

            return Math.round(cpuUse);
        } catch (Exception e) {
            // 备用方案：使用操作系统MXBean
            try {
                OperatingSystemMXBean osBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
                double cpuLoad = osBean.getSystemCpuLoad() * 100;
                return Math.round(cpuLoad);
            } catch (Exception ex) {
                return 0;
            }
        }
    }

    /**
     * 获取所有磁盘分区的使用情况
     *
     * @return 磁盘使用信息列表
     */
    public static List<DiskUsage> getDiskUsage() {
        List<DiskUsage> diskUsages = new ArrayList<DiskUsage>();
        File[] roots = File.listRoots();
        // 定义GB转换常量
        final long GB = 1024 * 1024 * 1024;
        if (roots != null) {
            for (File root : roots) {
                long totalSpace = root.getTotalSpace();
                long freeSpace = root.getFreeSpace();
                // 转换为GB（保留两位小数）
                double totalSpaceGB = (double) totalSpace / GB;
                double freeSpaceGB = (double) freeSpace / GB;
                double usagePercentage = 0;
                if (totalSpace > 0) {
                    usagePercentage = ((totalSpace - freeSpace) / (double) totalSpace) * 100;
                }
                if (totalSpace > 0 && !isVirtualDrive(root)) {
                    diskUsages.add(new DiskUsage(
                            root.getAbsolutePath(),
                            Math.round(totalSpaceGB),
                            Math.round(freeSpaceGB),
                            Math.round(usagePercentage)
                    ));
                }
            }
        }
        return diskUsages;
    }

    private static boolean isVirtualDrive(File root) {
        String path = root.getAbsolutePath().toLowerCase();
        // 常见的虚拟驱动器特征
        return path.contains("cd-rom") ||
                path.contains("dvd-rom") ||
                path.contains("virtual") ||
                path.contains("ramdisk") ||
                (root.getTotalSpace() > 0 && root.getFreeSpace() == root.getTotalSpace()); // 空的光驱
    }

    /**
     * 生成系统监控报告
     *
     * @return 格式化后的系统监控信息
     */
    public static String generateSystemReport(Integer memoryUsage, Double cpuUsage, List<DiskUsage> diskUsages) {
        StringBuilder report = new StringBuilder();
        report.append("========== 系统监控报告 ==========\n");
        // 内存信息
        report.append("内存使用率: ").append(memoryUsage).append("%\n");
        // CPU信息
        report.append("CPU 使用率: ").append(cpuUsage).append("%\n");
        // 磁盘信息
        report.append("磁盘使用情况:\n");
        for (DiskUsage disk : diskUsages) {
            double usedPercent = 0;
            if (disk.getTotalSpace() > 0) {
                usedPercent = (disk.getTotalSpace() - disk.getFreeSpace())
                        / (double) disk.getTotalSpace() * 100;
            }
            report.append("    ")
                    .append(disk.getPath())
                    .append(" 总空间：")
                    .append(disk.getTotalSpace())
                    .append("GB 剩余：")
                    .append(disk.getFreeSpace())
                    .append("GB 使用率：")
                    .append(String.format("%.2f", usedPercent))
                    .append("%\n");
        }
        report.append("=================================");
        return report.toString();
    }
}